cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...

        gameRoot: {
            default: null,
            type: cc.Node
        },
        settingRoot: {
            default: null,
            type: cc.Node
        },
        _gamecount: null,
        _seats: [],
        _timeLabel: null,
        _voiceMsgQueue: [],
        _playingSeat: null,
        _lastPlayTime: null,
        _seatsResult: [],
    },
    onLoad: function () {
        if (cc.vv == null) {
            return;
        }
        // cc.vv.audioMgr.playBGM("bgFight.mp3");
        cc.vv.common = this;
        cc.vv.gameNetMgr.isCurOver = false;
        var self = this;
        var seats = this.node.getChildByName("seats");
        for (var i = 0; i < seats.children.length; ++i) {
            this._seats.push(seats.children[i].getComponent("Seat"));
        }
        this._lblRoomNo = cc.find("Canvas/infobar/Z_room_txt/New Label").getComponent(cc.Label);
        this._lblRoomNo.string = cc.vv.gameNetMgr.roomId;
        this._timeLabel = cc.find("Canvas/infobar/time").getComponent(cc.Label);

        var _common = this.node.getChildByName('common');
        _common.active = !cc.vv.replayMgr.isReplay();
        this._gamecount = cc.find("Canvas/infobar/gamecount").getComponent(cc.Label);
        this._gamecount.string = "" + cc.vv.gameNetMgr.numOfGames + "/" + cc.vv.gameNetMgr.maxNumOfGames + "局";

        this.node.on('new_user', function (data) {
            console.log("new_user");
            self.refreshBtns();
            self.initSingleSeat(data.detail);
        });

        this.node.on('user_state_changed', function (data) {
            console.log("user_state_changed")
            self.initSeats(data.detail);
        });

        this.node.on('game_num', function (data) {
            console.log("game_num");
            self.refreshBtns();
            self._gamecount = cc.find("Canvas/infobar/gamecount").getComponent(cc.Label);
            self._gamecount.string = "" + cc.vv.gameNetMgr.numOfGames + "/" + cc.vv.gameNetMgr.maxNumOfGames + "局";
        });

        this.node.on('game_sync', function (data) {
            self._gamecount = cc.find("Canvas/infobar/gamecount").getComponent(cc.Label);
            self._gamecount.string = "" + cc.vv.gameNetMgr.numOfGames + "/" + cc.vv.gameNetMgr.maxNumOfGames + "局";
        });

        this.node.on('game_over', function (data) {
            var dataOver = data.detail.results;
            var seats = cc.vv.gameNetMgr.seats;
            for (var i = 0; i < seats.length; i++) {
                if (seats[i].userid != 0 && dataOver[i] != undefined) {
                    seats[i].curscore = dataOver[i].score;
                    seats[i].score = dataOver[i].totalscore;
                }
            }
            // self.initSeats();
        });

        this.node.on('game_curover', function (data) {
            self.refreshBtns();
        });

        this.node.on('game_end', function (data) {
            console.log("game_end");
            var resultList = cc.find("Canvas/game_result");
            resultList.active = true;

            var seatsList = resultList.getChildByName("seats");
            for (var i = 0; i < seatsList.children.length; ++i) {
                self._seatsResult.push(seatsList.children[i].getComponent("Seat"));
            }

            var endinfo = data.detail;
            var seats = cc.vv.gameNetMgr.seats;
            var maxscore = -1;
            for (var i = 0; i < seats.length; ++i) {
                var seat = seats[i];
                if (seat.userid != 0) {
                    if (seat.score > maxscore) {
                        maxscore = seat.score;
                    }
                }
            }
            for (var i = 0; i < seats.length; ++i) {
                var seat = seats[i];
                if (seat.userid != 0) {
                    var isBigwin = false;
                    if (seat.score > 0) {
                        isBigwin = seat.score == maxscore;
                    }
                    var isfangzhu = seat.userid == cc.vv.gameNetMgr.conf.creator;
                    self._seatsResult[i].setInfo(seat.name, seat.score, seat.curscore, isBigwin, isfangzhu);
                    self._seatsResult[i].setID(seat.userid);
                    self.showResult(self._seatsResult[i], endinfo[i]);
                }
            }
        });

        this.node.on('exit_room', function (data) {
            console.log("exit_room");
            var str = "";
            if (data.default.roomUser) {
                str = "房主退出会解散房间，请在当局结束后解散!"
            } else {
                str = "游戏正在进行中，请在当局结束后退出!";
            }
        });

        this.node.on('update_user_comes', function (data) {
            console.log("update_user_comes");
            self.initSeats();
        });

        this.node.on('remove_user_comes', function (data) {
            console.log("remove_user_comes");
            cc.vv.gameNetMgr.roomId = null;
            cc.vv.gameNetMgr.isOver = true;
            cc.director.loadScene("hall");
            self.initSeats();
        });

        this.node.on('chat_push', function (data) {
            console.log("chat_push")
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            // self._seats[localIdx].chat(data.content);
            self._seats[localIdx].chat(data.content);
        });

        this.node.on('quick_chat_push', function (data) {
            console.log("quick_chat_push")
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            var index = data.content;
            var info = cc.vv.chat.getQuickChatInfo(index, idx);
            self._seats[localIdx].chat(info.content);
            cc.vv.audioMgr.playSFX(info.sound);
        });

        this.node.on('voice_msg', function (data) {
            console.log("voice_msg")
            var data = data.detail;
            self._voiceMsgQueue.push(data);
            self.playVoice();
        });

        this.node.on('emoji_push', function (data) {
            console.log("emoji_push")
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            self._seats[localIdx].emoji(data.content);
        });

        this.node.on('game_defect', function (data) {
            console.log("game_defect");
            cc.vv.alert.show('在线人数不足两人，不能开局，快去邀请好友吧~');
            if (cc.vv.gameNetMgr.conf.type == 'mj') {
                var zhishai = cc.find('Canvas/arrow/btnKZ')
                zhishai.active = false;
            } else {
                var kaishi = cc.find('Canvas/arrow/kaishi')
                var guozhuang = cc.find('Canvas/arrow/guozhuang')
                kaishi.active = false;
                guozhuang.active = false;
            }
        });

        this.node.on('game_wait', function (data) {
            console.log("game_wait");
            cc.vv.alert.show('请耐心等待本局游戏结束后开始~');
        });

        this.node.on('dispress_push', function (data) {
            console.log('dispress_push')
            cc.vv.alert.show("房主" + 'asjdh' + "解散房间");
        });

        this.node.on('exit_notify', function (data) {
            console.log('exit_notify')
            cc.vv.alert.show('好友' + data.detail.name + '退出房间');
        });
    },

    showResult: function (seat, info) {
        for (var i in info) {
            seat.node.getChildByName(i).getComponent(cc.Label).string = info[i]
        }
    },

    refreshBtns: function () {
        var btnReady = cc.find("Canvas/arrow/btnReady");
        btnReady.active = cc.vv.gameNetMgr.isCurOver;
    },

    initSeats: function () {
        var seats = cc.vv.gameNetMgr.seats;
        for (var i = 0; i < seats.length; ++i) {
            this.initSingleSeat(seats[i]);
        }
    },

    initSingleSeat: function (seat) {
        var index = cc.vv.gameNetMgr.getLocalIndex(seat.seatindex);
        var isOffline = !seat.online && !cc.vv.replayMgr.isReplay();
        var isZhuang = seat.seatindex == cc.vv.gameNetMgr.button;
        var name = seat.name;
        this._seats[index].setInfo(name, seat.score, seat.curscore);
        this._seats[index].setReady(seat.ready && !cc.vv.gameNetMgr.gameState);
        this._seats[index].setOffline(isOffline);
        this._seats[index].setID(seat.userid);
        this._seats[index].voiceMsg(false);
        this._seats[index].setZhuang(isZhuang);
    },

    onBtnSettingsClicked: function () {
        cc.vv.popupMgr.showSettings();
    },

    onBtnWeichatClicked: function (data) {//分享
        var title = "<麻将>";
        if (cc.vv.gameNetMgr.conf.type == "mj") {
            title = "<麻将>";
        }

        if (cc.vv.gameNetMgr.conf.type == "nn") {
            title = "<牛牛>";
        }

        if (cc.vv.gameNetMgr.conf.type == "jdb") {
            title = "<九点半>";
        }

        cc.vv.anysdkMgr.share("小五牌坊" + title, "房号:" + cc.vv.gameNetMgr.roomId);
    },

    onBtnExit: function () {
        console.log("退出房间");
        //判断如果游戏未开始那就是退出，如果开始就解散 
        this.settingRoot.active = false;
        if (cc.vv.gameNetMgr.numOfGames == 0) {
            if (cc.vv.gameNetMgr.conf.creator == cc.vv.userMgr.userId) {
                cc.vv.alert.show("确定解散房间？", function () {
                    cc.vv.net.send("dispress");
                }, true);
            } else {
                cc.vv.alert.show("确定退出房间？", function () {
                    cc.vv.net.send("exit");
                }, true);
            }
        } else {
            cc.vv.net.send("dissolve_request");
        }

    },

    onBtnReadyClicked: function () {
        console.log("onBtnReadyClicked");
        cc.vv.net.send('ready');
        cc.vv.gameNetMgr.isCurOver = false;
        var seats = cc.vv.gameNetMgr.seats;
        for (var i = 0; i < seats.length; i++) {
            if (seats[i].userid != 0) {
                seats[i].curscore = null;
            }
        }
        if (cc.vv.gameNetMgr.conf.type == "mj") {
            this.gameRoot.active = false;
            var huType = cc.find("Canvas/arrow/huType");
            huType.active = false;
        } else if (cc.vv.gameNetMgr.conf.type == "nn" || cc.vv.gameNetMgr.conf.type == "jdb") {
            var zhuangPai = cc.find("Canvas/arrow/zhuangpai");
            var gameCard = cc.find("Canvas/game");
            var erguozhu = cc.find("Canvas/bet/betPos/poserguo/betZhu");
            var duimenbet = cc.find("Canvas/bet/betPos/posduimen/betZhu");
            var sifanbet = cc.find("Canvas/bet/betPos/possifan/betZhu");
            zhuangPai.active = false;
            erguozhu.active = false;
            duimenbet.active = false;
            sifanbet.active = false;
            var jumpDuration = 0.5;
            var typeNum = cc.vv.gameNetMgr.conf.type == "nn" ? 5 : 2;
            for (var i = 0; i < 4; i++) {
                for (var j = 0; j < typeNum + 1; j++) {
                    if (j < typeNum) {
                        gameCard.children[i].children[j].x = 0;
                        gameCard.children[i].children[j].y = 0;
                    }
                    gameCard.children[i].children[j].active = false;
                }
            }
            var selfZhu = cc.find("Canvas/bet/betPos");
            for (var i = 0; i < selfZhu.children.length; ++i) {
                var betZhu = selfZhu.children[i];
                for (var j = 0; j < betZhu.children.length; j++) {
                    var betZhuStr = betZhu.children[j].getComponent(cc.Label);
                    betZhuStr.string = 0;
                }
            }
        }
        this.refreshBtns();
        this.initSeats();
    },


    playVoice: function () {
        if (this._playingSeat == null && this._voiceMsgQueue.length) {
            console.log("playVoice2");
            var data = this._voiceMsgQueue.shift();
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this._playingSeat = localIndex;
            this._seats[localIndex].voiceMsg(true);

            var msgInfo = JSON.parse(data.content);

            var msgfile = "voicemsg.amr";
            cc.vv.voiceMgr.writeVoice(msgfile, msgInfo.msg);
            cc.vv.voiceMgr.play(msgfile);
            this._lastPlayTime = Date.now() + msgInfo.time;
        }
    },

    onPlayerOver: function () {
        cc.vv.audioMgr.resumeAll();
        console.log("onPlayCallback:" + this._playingSeat);
        var localIndex = this._playingSeat;
        this._playingSeat = null;
        // this._seats[localIndex].voiceMsg(false);
        this._seats[localIndex].voiceMsg(false);
    },

    onDestroy: function () {
        console.log("onDestroy");
        if (cc.vv) {
            cc.vv.gameNetMgr.clear();
        }
        cc.vv.voiceMgr.stop();
        //    cc.vv.voiceMgr.onPlayCallback = null;
    },
    onSex: function (i) {
        return cc.vv.gameNetMgr.seats[i].sex == 2 ? 'nv' : 'nan'

    },
    update: function (dt) {
        var minutes = Math.floor(Date.now() / 1000 / 60);
        if (this._lastMinute != minutes) {
            this._lastMinute = minutes;
            var date = new Date();
            var h = date.getHours();
            h = h < 10 ? "0" + h : h;

            var m = date.getMinutes();
            m = m < 10 ? "0" + m : m;
            this._timeLabel.string = "" + h + ":" + m;
        }

        if (this._lastPlayTime != null) {
            if (Date.now() > this._lastPlayTime + 200) {
                this.onPlayerOver();
                this._lastPlayTime = null;
            }
        }
        else {
            cc.vv.common.playVoice();
        }
    },
});
